# -*- coding: UTF-8 -*-
# @create  : 2024/9/2 10:16
# @Author  : 天空之城
# @File    : location_model.py
import re
import csv
import unicodedata

from address_normalizer.app.config import PROVINCE_CITY_DISTRICT


class LocationModel:

    @staticmethod
    def find_location(province, city, district, reference_data):
        # 过滤出可能的省市区组合
        possible_matches = [
            (prov, ct, dist) for prov, ct, dist in reference_data
            if (province is None or province in prov) and
               (city is None or city in ct) and
               (district is None or district in dist)
        ]

        # 如果唯一确定，则返回唯一的省市区组合
        if len(possible_matches) == 1:
            return possible_matches[0]

        # 否则返回None
        return (province, city, district)

    @staticmethod
    def check_location(province, city, district, reference_data):
        matches = 0
        for prov, ct, dist in reference_data:
            if prov == province and ct == city and dist == district:
                matches += 1
                if matches > 1:
                    return False
        return matches == 1

    @staticmethod
    def preprocess_address(address):
        # 去除空格和标点符号
        # address = re.sub(r'[^\w\s\(\)（）\-\#\]', '', address)
        address = address.replace(" ", "")
        # 将全角字符转换为半角字符
        address = LocationModel.fullwidth_to_halfwidth(address)

        return address

    @staticmethod
    # 全角转半角函数
    def fullwidth_to_halfwidth(ustring):
        """全角转半角"""
        return unicodedata.normalize('NFKC', ustring)

    @staticmethod
    def read_csv(file_path):
        data = []
        with open(file_path, mode='r', encoding='utf-8') as file:
            reader = csv.reader(file)
            next(reader)  # 跳过表头
            for row in reader:
                if len(row) == 3:
                    province, city, district = row
                    data.append((province, city, district))
        return data
